<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input style="max-width: 600px" placeholder="请输入中药材名称" v-model="queryInfo.query" clearable
                        @input="val => { queryInfo.query = val; handleSearchInput() }" @clear="getGoodsList">
                        <template #append>
                            <el-button :icon="Search" @click="getGoodsList()" />
                        </template>
                    </el-input>
                </el-col>

                <el-col :span="8">
                    <el-input style="max-width: 600px" placeholder="请输入中药材分类" v-model="queryInfo.category_query" clearable
                        @input="val => { queryInfo.category_query = val; handleSearchInput() }" @clear="getGoodsList">
                        <template #append>
                            <el-button :icon="Search" @click="getGoodsList()" />
                        </template>
                    </el-input>
                </el-col>

                <el-col :span="4">
                    <el-button v-if="hasPermission('添加商品功能')" type="primary" @click="addDialogVisible = true">添加商品</el-button>
                    <el-dialog v-model="addDialogVisible" title="添加商品" width="50%"
                        @close="() => addFormRef?.resetFields()">
                        <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
                            <el-form-item label="商品名称" prop="name">
                                <el-input v-model="addForm.name" />
                            </el-form-item>
                            <el-form-item label="商品分类" prop="category">
                                <el-cascader v-model="addForm.category" :options="cateOptions"
                                    :props="{ expandTrigger: 'hover', checkStrictly: true, emitPath: false, value: 'cat_id', label: 'cat_name' }" />
                            </el-form-item>
                            <el-form-item label="商品价格" prop="price">
                                <el-input-number v-model="addForm.price" :min="0" :precision="2" />
                            </el-form-item>
                            <el-form-item label="商品库存" prop="stock">
                                <el-input-number v-model="addForm.stock" :min="0" />
                            </el-form-item>
                            <el-form-item label="商品图片">
                                <el-upload list-type="picture-card" name="image" action="#" :auto-upload="false"
                                    :http-request="handleUpload" :file-list="addForm.images"
                                    :before-upload="beforeUpload" :on-remove="handleRemove" :on-change="handleUpload"
                                    :on-preview="handlePreview" class="upload-container">
                                    <el-icon size="24px">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </el-form-item>
                            <el-form-item label="商品描述">
                                <el-input v-model="addForm.description" type="textarea" :rows="4" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="addDialogVisible = false">取消</el-button>
                                <el-button type="primary" @click="submitAddForm">确定</el-button>
                            </span>
                        </template>
                    </el-dialog>
                </el-col>
            </el-row>

            <el-table :data="goodslist" stripe border class="responsive-table" height="450" style="width: 100%">
                <el-table-column type="index" label="#" width="50" />
                <el-table-column label="中药材名称" prop="name" min-width="120" />
                <el-table-column label="中药材分类" prop="category__name" min-width="100" />
                <el-table-column label="描述" prop="description" min-width="200" show-overflow-tooltip />
                <el-table-column label="商品价格(每斤/元)" prop="price" min-width="100" />
                <el-table-column label="商品库存" prop="stock" min-width="100" />
                <el-table-column label="中药材图片" width="140" align="center">
                    <template #default="scope">
                        <img v-if="scope.row.image" :src="'http://localhost:8000/' + scope.row.image"
                            class="product-image" alt="商品图片" />
                        <span v-else>暂无图片</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="created_at" min-width="180" :formatter="formatDate" />
                <el-table-column label="操作" fixed="right" width="180" align="center">
                    <template #default="scope">
                        <div class="operation-buttons">
                            <el-button type="primary" :icon="Edit" size="small" v-if="hasPermission('修改商品功能')" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button type="danger" :icon="Delete" size="small" v-if="hasPermission('删除商品功能')" @click="handleDelete(scope.row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 编辑商品对话框 -->
            <el-dialog v-model="editDialogVisible" title="编辑商品" width="50%" @close="() => editFormRef?.resetFields()">
                <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
                    <el-form-item label="商品名称" prop="name">
                        <el-input v-model="editForm.name" />
                    </el-form-item>
                    <el-form-item label="商品分类" prop="category">
                        <el-cascader v-model="editForm.category" :options="cateOptions"
                            :props="{ expandTrigger: 'hover', checkStrictly: true, emitPath: false, value: 'cat_id', label: 'cat_name' }" />
                    </el-form-item>
                    <el-form-item label="商品价格" prop="price">
                        <el-input-number v-model="editForm.price" :min="0" :precision="2" />
                    </el-form-item>
                    <el-form-item label="商品库存" prop="stock">
                        <el-input-number v-model="editForm.stock" :min="0" />
                    </el-form-item>
                    <el-form-item label="商品图片">
                        <el-upload list-type="picture-card" name="image" :file-list="editForm.images || []"
                            :before-upload="beforeUpload" :on-remove="handleEditRemove" :on-change="handleUpload"
                            :on-preview="handlePreview" :auto-upload="false">
                            <el-icon size="24px">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="商品描述">
                        <el-input v-model="editForm.description" type="textarea" :rows="4" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitEditForm">确定</el-button>
                    </span>
                </template>
            </el-dialog>


            <!-- 分页区域 -->
            <el-pagination v-model="queryInfo.page" :page-sizes="[1, 8, 16, 50]" :page-size="queryInfo.page_size"
                :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />

        </el-card>
    </div>
</template>
<script setup>
import { onMounted, watch } from 'vue';
import { ArrowRight, Edit, Delete, Plus } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es';
import Params from './Params.vue';  // 导入Params组件
import { ref } from 'vue';
import { ComponentSize } from 'element-plus'
import { Search } from '@element-plus/icons-vue';

// 添加权限检查函数
const hasPermission = (permission) => {
    const userFunctions = JSON.parse(sessionStorage.getItem('permissions') || '[]')
    return userFunctions.includes(permission)
}
import { ElMessage, ElMessageBox, ElCard } from 'element-plus';
import axios from '@/utils/http';

const goodslist = ref([])  // 商品列表数据
const currentPage4 = ref(4)
const size = ref < ComponentSize > ('default')
const background = ref(true)
const disabled = ref(false)
const addFormRef = ref(null);
// 日期格式化方法
const formatDate = (row) => {
    return row.created_at.slice(0, 19).replace('T', ' ')
}

const queryInfo = ref({
    query: '',  // 商品名称搜索
    category_query: '',  // 新增商品分类搜索
    page: 1,
    page_size: 8,
})
const total = ref(0)  // 总记录数
const handleSearchInput = debounce(() => {
    queryInfo.value.page = 1;
    getGoodsList();
}, 300);

// 监听分类查询变化
watch(() => queryInfo.value.category_query, () => {
    handleSearchInput();
});

const getGoodsList = async () => {
    const { data: res } = await axios.get('/api/products/all/', {
        params: {
            page: queryInfo.value.page,
            page_size: queryInfo.value.page_size,
            query: queryInfo.value.query,
            category_query: queryInfo.value.category_query
        }
    })
    console.log("商品的数据res：", res);
    if (res.code !== 200) return ElMessage.error(res.message)
    goodslist.value = res.data
    console.log("goodslist:", goodslist.value);
    console.log("总记录数:", res.total);
    total.value = res.total  // 使用接口返回的总记录数
}

const handleCurrentChange = (newPage) => {
    console.log("后面页码:", newPage);
    queryInfo.value.page = newPage
    getGoodsList()
}
const handleSizeChange = (newSize) => {
    console.log("*条/页:", newSize);
    queryInfo.value.page_size = newSize
    queryInfo.value.page = 1
    getGoodsList()
}
onMounted(() => {
    getGoodsList()
})

// 添加商品对话框显示状态
const addDialogVisible = ref(false)

// 表单数据对象
const addForm = ref({
    name: '',
    price: 0,
    stock: 99999,
    category: [],
    description: '',
    images: []
})

// 表单校验规则
const rules = ref({
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
    ],
    stock: [
        { required: true, message: '请输入商品库存', trigger: 'blur' },
        { type: 'integer', min: 0, message: '库存不能小于0', trigger: 'blur' }
    ]
})

// 提交新增商品
const submitAddForm = async () => {
    try {
        if (!addForm.value.category) return ElMessage.error('请选择商品分类');

        const formData = new FormData();
        formData.append('name', addForm.value.name);
        formData.append('price', Number(addForm.value.price));
        formData.append('stock', Number(addForm.value.stock));
        formData.append('description', addForm.value.description || '');
        formData.append('category_id', Number(addForm.value.category));

        addForm.value.images.forEach((file, index) => {
            if (file.raw) {
                formData.append('image', file.raw, file.raw?.name || `image_${index}`);
            }
        });

        const { data: res } = await axios.post('/api/products/', formData);

        if (res.code !== 200) {
            ElMessage.error(`操作失败：${res.message}`);
            return;
        }

        ElMessage.success('商品添加成功');
        addDialogVisible.value = false;
        addForm.value.images = [];
        addFormRef.value.resetFields();
        getGoodsList();
    } catch (err) {
        const message = err.response?.data?.message || err.message;
        ElMessage.error(`请求失败：${message}`);
    }
};

// 提交编辑商品
const submitEditForm = async () => {
    // 验证所有必要字段
    if (!editForm.value.name?.trim()) return ElMessage.error('请输入商品名称');
    if (editForm.value.price === undefined || editForm.value.price <= 0) return ElMessage.error('请输入有效的商品价格');
    if (editForm.value.stock === undefined || editForm.value.stock < 0) return ElMessage.error('请输入有效的商品库存');
    if (!editForm.value.category) return ElMessage.error('请选择商品分类');

    try {
        // 创建FormData处理文件上传
        const formData = new FormData();
        formData.append('name', editForm.value.name.trim());
        formData.append('price', Number(editForm.value.price).toFixed(2));
        formData.append('stock', Math.floor(Number(editForm.value.stock)));
        formData.append('description', editForm.value.description?.trim() || '');
        formData.append('category_id', Number(editForm.value.category));

        // 处理图片上传
        if (editForm.value.images?.[0]?.raw) {
            formData.append('image', editForm.value.images[0].raw);
        }

        const { data: res } = await axios.post(`/api/products/update/${editForm.value.id}/`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });

        if (res.code !== 200) throw new Error(res.message);
        ElMessage.success('更新成功');
        getGoodsList();
        editDialogVisible.value = false;
    } catch (err) {
        console.error('更新失败:', err);
        ElMessage.error(err.response?.data?.message || '更新操作失败，请检查网络或数据格式');
    }
};

// 获取商品分类选项
const cateOptions = ref([])

// 确保分类数据结构符合element-plus要求
const transformCategory = (data) => {
    return data.map(item => ({
        ...item,
        cat_id: item.id,  // 修正字段映射
        cat_name: item.name,  // 修正字段映射
        children: item.children ? transformCategory(item.children) : []
    }))
}
const getCateOptions = async () => {
    try {
        const { data: res } = await axios.get('/api/categories/', {
            params: {
                page: 1,
                page_size: 100  // 获取全部分类数据
            }
        })
        console.log("商品分类有：", res.data)
        if (res.code !== 200) return ElMessage.error('获取分类失败')
        cateOptions.value = transformCategory(res.data.list)
    } catch (err) {
        ElMessage.error('获取分类数据失败')
    }
}

// 图片上传成功处理
const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) ElMessage.error('只能上传图片格式!');
    if (!isLt2M) ElMessage.error('图片大小不能超过2MB!');
    return isImage && isLt2M;
}

const handleRemove = (file, fileList) => {
    addForm.value.images = fileList
}



const handleEditRemove = (file) => {
    const index = editForm.value.images.findIndex(img => img.uid === file.uid);
    if (index !== -1) {
        editForm.value.images.splice(index, 1);
    }
};

// 在组件挂载时获取分类数据
onMounted(() => {
    getGoodsList()
    getCateOptions()
})
const handleEdit = async (row) => {
    console.log("编辑的商品是：", row.id)
    const { data: res } = await axios.get(`/api/products/${row.id}/`)
    if (res.code !== 200) return ElMessage.error(res.message)
    editForm.value = {
        ...res.data,
        category: res.data.category_id ? [res.data.category_id] : [],
        images: res.data.image ? [{
            uid: Date.now(),
            name: res.data.image.split('/').pop(),
            url: `http://localhost:8000/${res.data.image}`,
            status: 'success'
        }] : []
    }
    editDialogVisible.value = true
}

// 处理图片上传
const handleUpload = (file) => {
    if (!file || !file.raw) return
    const isImage = file.raw.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('只能上传图片文件！')
        return false
    }
    const isLt2M = file.raw.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB！')
        return false
    }
    // 生成本地预览URL
    const previewUrl = URL.createObjectURL(file.raw)
    // 更新表单的images数组
    const imageData = {
        uid: Date.now(),
        name: file.name,
        raw: file.raw,
        url: previewUrl,
        status: 'ready'
    }
    if (editDialogVisible.value) {
        editForm.value.images = [imageData]
    } else {
        addForm.value.images = [imageData]
    }
    return false
}

// 图片预览处理函数
const handlePreview = (file) => {
    if (file.url) {
        window.open(file.url)
    }
}



const handleDelete = async (row) => {
    console.log("删除的商品是：", row.id)
    try {
        await ElMessageBox.confirm(`确定删除商品【${row.name}】吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const { data: res } = await axios.delete(`/api/products/delete/${row.id}/`)

        if (res.code !== 200) {
            // 处理特定的数据库错误
            if (res.message && res.message.includes('medicinal_categoryheadchild_recommended_products')) {
                ElMessage.error('无法删除商品：该商品可能被推荐商品列表引用')
            } else {
                ElMessage.error(res.message || '删除失败')
            }
            return
        }

        ElMessage.success('删除成功')
        getGoodsList()
    } catch (err) {
        if (err !== 'cancel') {
            // 处理其他类型的错误
            const errorMsg = err.response?.data?.message || '删除失败，请稍后重试'
            ElMessage.error(errorMsg)
        } else {
            ElMessage.info("已取消删除")
        }
    }
}

const editDialogVisible = ref(false)
const editForm = ref({
    id: 0,
    name: '',
    price: 0,
    stock: 0,
    category: [],
    description: '',
    images: []
})
</script>

<style scoped>
/* 卡片样式优化 */
.el-card {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    /* margin-bottom: 50px; */
    background: #fff;
}

/* 搜索区域样式 */
.el-row {
    margin-bottom: 24px;
}

.el-input {
    border-radius: 8px;
    transition: all 0.3s ease;
}

.el-input:hover {
    transform: translateY(-1px);
}

.operation-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.operation-buttons .el-button {
    margin: 0;
    padding: 4px 12px;
    font-size: 12px;
}

/* 表格样式优化 */
.el-table {
    border-radius: 8px;
    overflow: hidden;
    margin: 16px 0;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.el-table th {
    background-color: #f8f9fa !important;
    color: #333;
    font-weight: 600;
    padding: 12px 0;
}

.el-table td {
    padding: 16px 0;
}

/* 按钮样式优化 */
.el-button {
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-button--primary {
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
}

.el-button--danger {
    background: linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%);
}

/* 图片样式优化 */
.product-image {
    width: 120px;
    height: 120px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.product-image:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 上传组件样式 */
.upload-container .el-upload--picture-card {
    border-radius: 8px;
    border: 2px dashed #d9d9d9;
    background: #fafafa;
    transition: all 0.3s ease;
}

.upload-container .el-upload--picture-card:hover {
    border-color: #1890ff;
    background: #f0f5ff;
}

.upload-container .el-upload-list--picture-card {
    max-height: 240px;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    padding: 8px;
}

.upload-container .el-upload-list--picture-card .el-upload-list__item {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    margin: 0;
    transition: all 0.3s ease;
}

/* 分页器样式 */
.el-pagination {
    margin-top: 24px;
    padding: 16px 0;
    justify-content: center;
}

.el-pagination .el-pagination__total,
.el-pagination .el-pagination__sizes {
    margin-right: 16px;
}

/* 对话框样式 */
.el-dialog {
    border-radius: 16px;
    overflow: hidden;
}

.el-dialog__header {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
    margin: 0;
}

.el-dialog__body {
    padding: 24px;
}

.el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    margin: 0;
}

/* 表单样式 */
.el-form-item {
    margin-bottom: 24px;
}

.el-form-item__label {
    font-weight: 500;
    color: #333;
}

.el-input-number {
    width: 100%;
}

/* 级联选择器样式 */
.el-cascader {
    width: 100%;
}


/* 响应式布局样式 */
@media screen and (max-width: 1200px) {
    .el-row {
        flex-direction: column;
    }
    .el-col {
        width: 100% !important;
        margin-bottom: 16px;
    }
}

@media screen and (max-width: 768px) {
    .responsive-table {
        width: 100%;
        overflow-x: auto;
    }
    .el-button {
        padding: 8px 12px;
        font-size: 12px;
    }
    .product-image {
        width: 80px;
        height: 80px;
    }
}

/* 表格响应式滚动 */
.responsive-table {
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

/* 保持现有样式 */
.el-table {
    border-radius: 8px;
    overflow: hidden;
    margin: 16px 0;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.el-table th {
    background-color: #f8f9fa !important;
    color: #333;
    font-weight: 600;
    padding: 12px 0;
}

.el-table td {
    padding: 16px 0;
}

/* 按钮样式优化 */
.el-button {
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.el-button--primary {
    background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
}

.el-button--danger {
    background: linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%);
}

/* 图片样式优化 */
.product-image {
    width: 120px;
    height: 120px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.product-image:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 上传组件样式 */
.upload-container .el-upload--picture-card {
    border-radius: 8px;
    border: 2px dashed #d9d9d9;
    background: #fafafa;
    transition: all 0.3s ease;
}

.upload-container .el-upload--picture-card:hover {
    border-color: #1890ff;
    background: #f0f5ff;
}

.upload-container .el-upload-list--picture-card {
    max-height: 240px;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    padding: 8px;
}

.upload-container .el-upload-list--picture-card .el-upload-list__item {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    margin: 0;
    transition: all 0.3s ease;
}

/* 分页器样式 */
.el-pagination {
    margin-top: 24px;
    padding: 16px 0;
    justify-content: center;
}

.el-pagination .el-pagination__total,
.el-pagination .el-pagination__sizes {
    margin-right: 16px;
}

/* 对话框样式 */
.el-dialog {
    border-radius: 16px;
    overflow: hidden;
}

.el-dialog__header {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
    margin: 0;
}

.el-dialog__body {
    padding: 24px;
}

.el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    margin: 0;
}

/* 表单样式 */
.el-form-item {
    margin-bottom: 24px;
}

.el-form-item__label {
    font-weight: 500;
    color: #333;
}

.el-input-number {
    width: 100%;
}

/* 级联选择器样式 */
.el-cascader {
    width: 100%;
}
</style>
